var app = getApp();
var Const = require('./../../utils/const.js');
const Zan = require('../../dist/index');

var amapFile = require('../../libs/amap-wx.js');
var config = require('../../libs/config.js');

Page(Object.assign({}, Zan.TopTips, {
	data: {
		offset: {
			width: '100%',
			height: '100%'
		},
		user: {
			isLogin: false,
			networkActive: false,
			checkIdcard: false,
			payForegift: false,
			payWallet: false
		},
		mapConfig: {
			width: wx.getSystemInfoSync().windowWidth,
			height: wx.getSystemInfoSync().windowHeight
		},
		isInit: true,
		isHided: false,
		isCabinet: true,
		isWait: false,
		current: {},
		currentInfo: {},
		currentEndpoint: null,
		lastEndpoint: null,
		markers: [],
		polyline: [],
		distance: 0,
		cost: 0,
		selectMarker: {}
	},
	onLoad: function () {
		this.mapConfig();
	},

	onShow: function () {
		this.init();
	},

	init: function () {
		var that = this, isMapCabinet = app.data.isMapCabinet;
		// testing is login
		if (app.data.token) {
			app.battery.testLogin().then(function (r) {
				that.testLoginSuccess(r);
			}).catch(function (e) {
				that.showZanTopTips(e.message, {type: 'error'});
			});
		} else {
			// clean login info
			that.setData({
				user: {
					isLogin: false,
					networkActive: false,
					checkIdcard: false,
					payForegift: false,
					payWallet: false
				}
			});
			that.tabControlSix(true);
		}

		if (!isMapCabinet) {
			isMapCabinet = true;
			that.setData({
				isCabinet: isMapCabinet
			});
			that.tabControlSix();
			return false;
		}

		wx.getLocation({
			type: 'gcj02',
			success: function (res) {
				that.setData({
					current: {
						latitude: res.latitude,
						longitude: res.longitude
					}
				});
			},
			fail: function () {
				console.log('数据异常');
				//wx.showToast({
				//	title: '数据异常',
				//	image: '/image/toast-warm.png',
				//	duration: 2000
				//})
			}
		});

		wx.getLocation({
			type: 'wgs84',
			success: function (res) {
				//get near cabinet 5km radius
				if (that.data.isCabinet) {
					that.reqCabinet(res);
				} else {
					that.reqNetwork(res);
				}
			},
			fail: function () {
				console.log('数据异常');
				//wx.showToast({
				//	title: '数据异常',
				//	image: '/image/toast-warm.png',
				//	duration: 2000
				//})
			}
		});

		if (that.data.isInit) {
			that.setData({
				isInit: false
			});
		}

		that.mapCtx.moveToLocation();
	},

	regionchange(e) {
		var that = this;
		if (e.type == 'end') {
			//get center position
			that.mapCtx.getCenterLocation({
				success: function (res) {
					if (that.data.isCabinet) {
						that.reqCabinet(res);
					} else {
						that.reqNetwork(res);
					}
				}
			})
		}
	},

	markertap(e) {
		var that = this;
		let key = config.Config.key;
		let myAmap = new amapFile.AMapWX({key: key});

		if (!that.data.isCabinet && e.markerId != null && e.markerId != undefined) {
			var markers = that.data.markers;
			for (var i in markers) {
				if (markers[i].id == e.markerId) {
					this.setData({
						selectMarker: markers[i]
					});
					myAmap.getDrivingRoute(this.getDataObj());
				}
			}
		} else {
			if (e.markerId) {
				//go to detail page
				wx.navigateTo({
					url: '/pages/cabinet/cabinet?id=' + e.markerId
				})
			}
		}
	},

	getDataObj() {
		let $this = this;
		return {
			origin: this.data.current.longitude + ',' + this.data.current.latitude,
			destination: this.data.selectMarker.longitude + ',' + this.data.selectMarker.latitude,
			success(data) {
				let points = [];
				if (!data.paths || !data.paths[0] || !data.paths[0].steps) {
					wx.showToast({ title: '地址解析失败!' });
					return;
				}

				if (data.paths && data.paths[0] && data.paths[0].steps) {
					var steps = data.paths[0].steps;
					for (var i = 0; i < steps.length; i++) {
						var poLen = steps[i].polyline.split(';');
						for (var j = 0; j < poLen.length; j++) {
							points.push({
								longitude: parseFloat(poLen[j].split(',')[0]),
								latitude: parseFloat(poLen[j].split(',')[1])
							})
						}
					}
				}

				$this.setData({
					distance: data.paths[0].distance / 1000.0,
					cost: parseInt(data.paths[0].duration / 60),
					polyline: [{
						points: points,
						color: "#0091ff",
						width: 6
					}]
				});
			},
			fail(info) {
				wx.showToast({ title: '失败！' })
			}
		}
	},

	goToNetWork: function() {
		let marker = this.data.selectMarker;
		wx.openLocation({
			latitude: marker.latitude,
			longitude: marker.longitude,
			scale: 18,
			name: marker.name,
			address: marker.address
		})
	},

	controltap(e) {
		var that = this;
		//recurrent
		this.setData({
			selectMarker: null,
			polyline: [],
			distance: 0,
			cost: 0
		});

		if (e.controlId == 1) {
			that.mapCtx.moveToLocation();
		} else if (e.controlId == 3) {
			//如果用户没登录，提示登录
			app.battery.testLogin().then(function (r) {
				if (!r) {
					wx.showModal({
						title: '',
						content: '请先登录',
						success: function (res) {
							if (res.confirm) {
								// 跳转到登录
								wx.navigateTo({
									url: '/pages/user/login/login?type=' + Const.TOPTIPS.WARN + '&msg=' + Const.ERROR_MSG.NOT_LOGIN
								})
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else {
					// 扫描之前看看有没有欠费
					that.silenceLogin(null, function () {
						that._commonScanCode();
					});
				}
			}).catch(function (e) {
				that.showZanTopTips(e.message, {type: 'error'});
			});
		} else if (e.controlId == 4) {
			wx.navigateTo({
				url: '/pages/setting/setting'
			})
		} else if (e.controlId == 5) {
			// 直接判断有没有登录，没登录就去登录页面
			let is_auth = wx.getStorageSync(Const.DATA.KEY_AUTH);
			if (!that.data.user.isLogin) {
				if (!is_auth) {
					wx.navigateTo({
						url: '/pages/user/auth/index'
					})
				} else {
					wx.navigateTo({
						url: '/pages/user/login/login?type=' + Const.TOPTIPS.WARN + '&msg=' + Const.ERROR_MSG.NOT_LOGIN
					})
				}
			} else {
				wx.navigateTo({
					url: '/pages/user/index/index'
				})
			}
		} else if (e.controlId == 6) {
			that.tabControlSix();
		} else if (e.controlId == 7) {
			wx.navigateTo({
				url: '/pages/user/login/login?type=' + Const.TOPTIPS.WARN + '&msg=' + Const.ERROR_MSG.NOT_LOGIN
			})
		} else if (e.controlId == 8) {
			if (that.data.isCabinet) {
				that.tabControlSix();
			}
		} else if (e.controlId == 9) {
			wx.navigateTo({
				url: '/pages/user/idcard/idcard'
			})
		} else if (e.controlId == 10) {
			// pay deposit

		} else if (e.controlId == 11) {
			wx.navigateTo({
				url: '/pages/recharge/recharge'
			})
		} else if (e.controlId == 12) {
			// 刷新
			that.init();
		}
	},

	_commonScanCode: function () {
		var that = this;

		let payWallet = app.data.member.payWallet;
		let walletMoney = app.data.member.walletMoney;
		let tradeMoney = app.data.member.tradeMoney;
		let monthExpireTime = app.data.member.monthExpireTime;
		let monthWalletMoney = app.data.member.monthWalletMoney;
		let monthTradeMoney = app.data.member.monthTradeMoney;

		if (!payWallet) {
			that.showMoneyLackModal();
			return;
		}

		if (monthExpireTime && (monthWalletMoney - monthTradeMoney) <= 0 && (walletMoney - tradeMoney) <= 0) {
			that.showMoneyLackModal();
			return;
		}

		if (!monthExpireTime && (walletMoney - tradeMoney) <= 0) {
			that.showMoneyLackModal();
			return;
		}

		wx.scanCode({
			onlyFromCamera: true, // 只允许从相机扫码
			success: (res) => {
				if (res.result != null) {
					app.battery.common('sweepCode', {
						cabinetNumber: res.result,
						ticket: app.data.token
					}).then(function (r) {
						if (!r || r.code != 0) {
							wx.showToast({
								title: '操作成功',
								icon: 'success',
								duration: 1000
							})
							//wx.navigateTo({
							//	url: '/pages/user/clogin/clogin?cabinetNumber=' + res.result
							//})
						} else {
							that.showZanTopTips(r.message, {type: 'error'});
						}
					}).catch(function (e) {
						that.showZanTopTips(e.message, {type: 'error'});
					});
				}
			}
		})
	},

	showMoneyLackModal: function () {
		wx.showModal({
			title:'提示',
			content: '余额不足, 请充值',
			duration: 1000,
			success: function(res){
				if (res.cancel) {
					//点击取消,默认隐藏弹框
				} else {
					//点击确定
					wx.navigateTo({
						url: '/pages/recharge/recharge'
					})
				}
			}
		});
	},

	getCenterLocation: function () {
		this.mapCtx.getCenterLocation({
			success: function (res) {
			}
		})
	},

	moveToLocation: function () {
		this.mapCtx.moveToLocation()
	},

	reqCabinet: function (position) {
		if (position && position.latitude && position.longitude) {
			var that = this;
			var markers = [];
			app.battery.common('cabinet/list', {
				ticket: app.data.token,
				lat: position.latitude,
				lng: position.longitude,
				radius: 5000
			}).then(function (d) {
				var width = that.data.mapConfig.width * 0.15;
				for (var i in d) {
					var reservableCount = 0;
					for (let t in d[i].batteryInCabinetModel) {
						let battery = d[i].batteryInCabinetModel[t];
						if (battery && battery.useStatus <= 0 && battery.chargerStatus == 1 && battery.curPower >= 98) {
							reservableCount += 1;
						}
					}
					markers.push({
						"id": d[i].id,
						"latitude": d[i].gpsLat,
						"longitude": d[i].gpsLng,
						"width": width,
						"height": width,
						"iconPath": `/image/map/map-sign-battery${reservableCount}.png`,
						"callout": {
							"content": d[i].name,
							"padding": 5,
							"borderRadius": 5,
							"fontSize": 13
						}
					});
				}
				that.setData({
					markers: markers,
					lastPosition: position
				});
			}).catch(function (e) {
				that.showZanTopTips(e.message, {type: 'error'});
			});
		}
	},

	reqNetwork: function (position) {
		if (position && position.latitude && position.longitude) {
			if (app.data.token) {
				var that = this;
				var markers = [];

				//temp change after api complate
				app.battery.common('network/list', {
					ticket: app.data.token,
					lat: position.latitude.toFixed(5),
					lng: position.longitude.toFixed(5),
					radius: 5000
				}).then(function (d) {
					console.log(d);
					var width = that.data.mapConfig.width * 0.15;
					for (var i in d) {
						markers.push({
							"id": d[i].id,
							"latitude": d[i].gpsLat,
							"longitude": d[i].gpsLng,
							"width": width,
							"height": width,
							"name": d[i].name,
							"address": d[i].address,
							"iconPath": "/image/map/map-sign-network.png",
							"callout": {
								"content": d[i].name,
								"padding": 5,
								"borderRadius": 5,
								"fontSize": 13
							}
						});
					}
					that.setData({
						markers: markers,
						lastPosition: position
					});
				}).catch(function (e) {
					that.showZanTopTips(e.message, {type: 'error'});
				});
			} else {
				this.showZanTopTips('请先登陆', {type: 'error'});
			}
		}
	},

	tabControlSix: function (isFlash) {
		var that = this, isCabinet = that.data.isCabinet, iconPath, lastPosition = that.data.lastPosition;

		var controls = [{
			id: 1,
			iconPath: '/image/map/map-icon-current.png',
			position: {top: that.data.mapConfig.height - 140, left: 20, width: 45, height: 45},
			clickable: true
		}, {
			id: 2,
			iconPath: '/image/map/map-icon-current-position.png',
			position: {
				top: that.data.mapConfig.height / 2 - 40,
				left: (that.data.mapConfig.width - 40) / 2,
				width: 40,
				height: 40
			},
			clickable: false
		}, {
			id: 3,
			iconPath: '/image/map/default-btn-scren.png',
			position: {
				top: that.data.mapConfig.height - 76,
				left: (that.data.mapConfig.width - 150) / 2,
				width: 150,
				height: 40
			},
			clickable: true
		}, {
			id: 4,
			iconPath: '/image/map/map-icon-setting.png',
			position: {top: that.data.mapConfig.height - 80, left: 20, width: 45, height: 45},
			clickable: true
		}, {
			id: 5,
			iconPath: '/image/map/map-icon-user.png',
			position: {
				top: that.data.mapConfig.height - 80,
				left: that.data.mapConfig.width - 58.5,
				width: 58.5,
				height: 45
			},
			clickable: true
		}];

		if (!isFlash) {
			if (that.data.isCabinet) {
				isCabinet = false;
				that.reqNetwork(lastPosition);
			} else {
				isCabinet = true;
				that.reqCabinet(lastPosition);
			}
		} else {

		}
		controls.push({
			id: 6,
			iconPath: isCabinet ? '/image/map/map-icon-network.png' : '/image/map/map-icon-battery.png',
			position: {
				top: that.data.mapConfig.height - 200,
				left: 20,
				width: 45,
				height: 45
			},
			clickable: true
		});
		if (!that.data.user.isLogin) {
			controls.push({
				id: 7,
				iconPath: '/image/map/index-tips-login.png',
				position: {
					top: 10,
					left: 10,
					width: that.data.mapConfig.width - 20,
					height: (that.data.mapConfig.width - 20) * 0.2
				},
				clickable: true
			});
		} else if (!that.data.user.networkActive) {
			controls.push({
				id: 8,
				iconPath: '/image/map/index-tips-activation.png',
				position: {
					top: 10,
					left: 10,
					width: that.data.mapConfig.width - 20,
					height: (that.data.mapConfig.width - 20) * 0.2
				},
				clickable: true
			});
		} else if (!that.data.user.checkIdcard) {
			controls.push({
				id: 9,
				iconPath: '/image/map/index-tips-checkid.png',
				position: {
					top: 10,
					left: 10,
					width: that.data.mapConfig.width - 20,
					height: (that.data.mapConfig.width - 20) * 0.2
				},
				clickable: true
			});
		} else if (!that.data.user.payForegift) {
			controls.push({
				id: 10,
				iconPath: '/image/map/index-tips-desposit.png',
				position: {
					top: 10,
					left: 10,
					width: that.data.mapConfig.width - 20,
					height: (that.data.mapConfig.width - 20) * 0.2
				},
				clickable: true
			});
		} else if (!that.data.user.payWallet) {
			controls.push({
				id: 11,
				iconPath: '/image/map/index-tips-recharge.png',
				position: {
					top: 10,
					left: 10,
					width: that.data.mapConfig.width - 20,
					height: (that.data.mapConfig.width - 20) * 0.2
				},
				clickable: true
			});
		}

		controls.push({
			id: 12,
			iconPath: '/image/map/map-icon-fresh.png',
			position: {
				top: that.data.mapConfig.height - 260,
				left: 20,
				width: 45,
				height: 45
			},
			clickable: true
		});

		that.setData({
			isCabinet: isCabinet
		});

		setTimeout(function () {
			that.setData({
				controls: controls
			});
		}, 200);

	},

	silenceLogin: function (r, fn) {
		var that = this;
		if (!r) {
			that.setData({
				user: {
					isLogin: false
				}
			});
			if (app.data.token) {
				//login
				app.wechat.login().then(function (res) {
					if (res.code) {
						//发起网络请求
						app.battery.common('silenceLogin', {code: res.code}).then(function (d) {
							if (d.ticket) {
								that.setData({
									user: {
										isLogin: true,
										balance: d.member.walletMoney,
										avatar: d.member.avatar,
										nickName: d.member.name,
										bindWebchat: d.member.bindWebchat,
										checkIdcard: d.member.checkIdcard,
										checkMobile: d.member.checkMobile,
										foregiftMoney: d.member.foregiftMoney,
										networkActive: d.member.networkActive,
										payForegift: d.member.payForegift,
										payWallet: d.member.payWallet
									}
								});
								//save token
								app.data.token = d.ticket;
								app.data.member = d.member;
								app.wechat.setStorage(Const.DATA.KEY_TOKEN, d.ticket);
								app.wechat.setStorage(Const.DATA.KEY_MEMBER, d.member);
								fn && fn();
							} else {
								fn && fn();
								//that.showTopTips(d.message, {type: 'error'});
							}
						});
					} else {
						that.showTopTips('获取用户登录状态失败！' + res.errMsg, {type: 'error'});
					}
				}).catch(function (e) {
					console.log('---静默登录异常---');
					that.showTopTips(e.errMsg, {type: 'error'});
				});
			} else {
				fn && fn();
			}
		} else if (r) {
			that.setData({
				user: {
					isLogin: true,
					balance: r.walletMoney,
					avatar: r.avatar,
					nickName: r.name,
					bindWebchat: r.bindWebchat,
					checkIdcard: r.checkIdcard,
					checkMobile: r.checkMobile,
					foregiftMoney: r.foregiftMoney,
					networkActive: r.networkActive,
					payForegift: r.payForegift,
					payWallet: r.payWallet
				}
			});
			fn && fn();
		}
	},

	testLoginSuccess: function (r) {
		var that = this;
		if (r || app.data.token) {
			that.silenceLogin(r, function () {
				that.tabControlSix(true);
				// 获取我的预约
				console.log("我的预约");
				that.getCurrentSubscribe();
			});
		} else {
			that.tabControlSix(true);
		}
	},

	mapConfig: function () {
		var that = this;

		// 使用 wx.createMapContext 获取 map 上下文
		that.mapCtx = wx.createMapContext('map');
		var query = wx.createSelectorQuery();
		query.select('#map').boundingClientRect();
		query.selectViewport().scrollOffset();
		query.exec(function (res) {
			var controls = [{
				id: 1,
				iconPath: '/image/map/map-icon-current.png',
				position: {top: res[0].height - 140, left: 20, width: 45, height: 45, 'z-index': 10},
				clickable: true
			}, {
				id: 2,
				iconPath: '/image/map/map-icon-current-position.png',
				position: {top: res[0].height / 2 - 54, left: (res[0].width - 30) / 2, width: 30, height: 54, 'z-index': 10},
				clickable: false
			}, {
				id: 3,
				iconPath: '/image/map/default-btn-scren.png',
				position: {top: res[0].height - 76, left: (res[0].width - 150) / 2, width: 150, height: 40, 'z-index': 10},
				clickable: true
			}, {
				id: 4,
				iconPath: '/image/map/map-icon-setting.png',
				position: {top: res[0].height - 80, left: 20, width: 45, height: 45, 'z-index': 10},
				clickable: true
			}, {
				id: 5,
				iconPath: '/image/map/map-icon-user.png',
				position: {top: res[0].height - 80, left: res[0].width - 58.5, width: 58.5, height: 45, 'z-index': 10},
				clickable: true
			}];
			controls.push({
				id: 6,
				iconPath: '/image/map/map-icon-network.png',
				position: {
					top: res[0].height - 200,
					left: 20,
					width: 45,
					height: 45,
					'z-index': 10
				},
				clickable: true
			});
			controls.push({
				id: 12,
				iconPath: '/image/map/map-icon-fresh.png',
				position: {
					top: res[0].height - 260,
					left: 20,
					width: 45,
					height: 45,
					'z-index': 10
				},
				clickable: true
			});

			//set center position
			that.setData({
				mapConfig: {
					width: res[0].width,
					height: res[0].height
				},
				controls: controls
			});
		});
	},

	maptap: function (e) {
		console.log(e);
	},

	getCurrentSubscribe: function () {
		var that = this;

		app.battery.findOne('subscribe/current', {
			ticket: app.data.token
		}).then(function (r) {
			if (r && r.code <= 0) {
				app.wechat.setStorage(Const.DATA.KEY_SUBSCRIBE_CODE, "");
				return;
			}

			app.wechat.getStorage(Const.DATA.KEY_SUBSCRIBE_CODE).then(function (res) {
				let code = res.data;
				if (!code) {
					return;
				}
				wx.showModal({
					title: '电池预约提示',
					content: "您的电池预约码是" + code + ", 是否导航",
					success: function (res) {
						if (res.confirm) {
							wx.openLocation({
								latitude: r.batteryCabinetLat,
								longitude: r.batteryCabinetLng,
								name: r.batteryCabinetName,
								scale: 28
							})
						} else if (res.cancel) {
							console.log('用户点击取消')
						}
					}
				})
			});

		}).catch(function (e) {
			that.showZanTopTips(e.message, {type: 'error'});
		});
	},

	showTopTips: function (msg) {
		this.showZanTopTips(msg);
	},

	goToNetWorkListPage: function () {
		wx.navigateTo({
			url: '/pages/network/network'
		})
	}
}));
